package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-pro/cache"
	"recruit-pro/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "2"))
	offset := (page - 1) * pageSize
	var total int64
	models.DB.Model(&models.Models{}).Count(&total)
	var arr []models.Models
	redis_key := "redis_list_"
	RedisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if RedisData == "" {
		models.DB.Offset(offset).Limit(pageSize).Order("ID DESC").Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(RedisData), &arr)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  arr,
		"total": total,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var arr models.Models
	redis_key := "redis_detail_" + id
	RedisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if RedisData == "" {
		models.DB.Where("id=?", id).Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(RedisData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
func Coll(c *gin.Context) {
	id := c.Query("id")
	var arr models.Models
	redis_key := "redis_col_" + id
	RedisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if RedisData == "" {
		models.DB.Where("id=?", id).Create(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(RedisData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
